import React from 'react';
import { Card, Table, Button, Input, Modal, Form, Space, message } from 'antd';

// 产品类型页面（模仿 admin-web 的 ProductType.vue）
export default function ProductType() {
  // 搜索与分页
  const [searchForm] = Form.useForm();
  const [search, setSearch] = React.useState({ name: '' });
  const [pageIndex, setPageIndex] = React.useState(1);
  const [pageSize, setPageSize] = React.useState(10);
  const [loading, setLoading] = React.useState(false);

  // 列表数据（模拟）
  const [list, setList] = React.useState(() => ([
    { id: 1, name: '饮料', notes: '瓶装/罐装饮品', createTime: '2025-09-10 14:32' },
    { id: 2, name: '零食', notes: '饼干、膨化食品等', createTime: '2025-09-12 10:15' },
    { id: 3, name: '日用品', notes: '纸巾、牙刷等', createTime: '2025-09-15 09:01' },
  ]));

  // 新增/编辑
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [form] = Form.useForm();

  // 过滤与分页
  const filtered = React.useMemo(() => {
    let data = list;
    if (search.name) data = data.filter(i => String(i.name).includes(search.name));
    return data;
  }, [list, search]);

  const pageData = React.useMemo(() => {
    const start = (pageIndex - 1) * pageSize;
    return filtered.slice(start, start + pageSize);
  }, [filtered, pageIndex, pageSize]);

  const columns = [
    { title: '类型名称', dataIndex: 'name', align: 'center' },
    { title: '备注', dataIndex: 'notes' },
    { title: '创建时间', dataIndex: 'createTime', width: 160, align: 'center' },
    {
      title: '操作',
      fixed: 'right',
      width: 100,
      align: 'center',
      render: (_, row) => (
        <Button size="small" onClick={() => editProductType(row)}>编辑</Button>
      ),
    },
  ];

  // 搜索
  const onSearchSubmit = async () => {
    const values = await searchForm.validateFields();
    setSearch(values);
    setPageIndex(1);
  };
  const onResetSearch = () => {
    searchForm.resetFields();
    setSearch({ name: '' });
    setPageIndex(1);
  };

  // 弹窗操作
  const addProductType = () => {
    setEditing(null);
    form.resetFields();
    setDialogOpen(true);
  };
  const editProductType = (row) => {
    setEditing(row);
    form.setFieldsValue({ name: row.name, notes: row.notes });
    setDialogOpen(true);
  };
  const onSave = async () => {
    const values = await form.validateFields();
    if (editing) {
      setList(prev => prev.map(i => i.id === editing.id ? { ...i, ...values } : i));
      message.success('产品类型已更新');
    } else {
      const maxId = Math.max(0, ...list.map(i => i.id));
      setList(prev => [{ id: maxId + 1, createTime: new Date().toLocaleString(), ...values }, ...prev]);
      message.success('产品类型已新增');
    }
    setDialogOpen(false);
  };

  return (
    <div style={{ display: 'grid', gap: 16 }}>
      <Card variant="borderless">
        <Form form={searchForm} layout="inline" initialValues={search} style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <Form.Item name="name" label="类型名称">
            <Input allowClear placeholder="请输入类型名称" style={{ width: 220 }} />
          </Form.Item>
          <Space>
            <Button type="primary" onClick={onSearchSubmit}>查询</Button>
            <Button onClick={onResetSearch}>重置</Button>
            <Button type="dashed" onClick={addProductType}>新增类型</Button>
          </Space>
        </Form>
      </Card>

      <Card title="产品类型清单" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r) => r.id}
          loading={loading}
          dataSource={pageData}
          columns={columns}
          pagination={{
            current: pageIndex,
            pageSize,
            total: filtered.length,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            onChange: (pi, ps) => { setPageIndex(pi); setPageSize(ps); },
          }}
        />
      </Card>

      <Modal title={editing ? '编辑产品类型' : '新增产品类型'} open={dialogOpen} onOk={onSave} onCancel={() => setDialogOpen(false)}>
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="类型名称" rules={[{ required: true, message: '请输入类型名称' }]}> 
            <Input />
          </Form.Item>
          <Form.Item name="notes" label="备注"> 
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}